import http from '@ohos.net.http';
import router from "@system.router";

const BASEURL = "http://101.32.223.115:3002/api";
const SUCCESS = 0;
const PLUS = 1001;
const GETAUTHORIZATION = 1002;
const SETAUTHORIZATION = 1003;

export async function sleep(timeout) {
    return new Promise((resolve) => {
        setTimeout(resolve, timeout);
    })
}

export async function plus(params) {
    try {
        const action = {};
        action.bundleName = "com.sengmitnick.timelogger";
        action.abilityName = "com.sengmitnick.timelogger.ServiceAbility";
        action.data = params;
        action.messageCode = PLUS;
        action.abilityType = 0;

        var result = await FeatureAbility.callAbility(action);
        var ret = JSON.parse(result);
        if (ret.code == 0) {
            console.info('plus result is:' + JSON.stringify(ret.abilityResult));
        } else {
            console.error('plus error code:' + JSON.stringify(ret.code));
        }
    } catch (err) {
        console.error('plus failed. Cause: ' + JSON.stringify(err));
    }
    return
}

export async function getAuthorization() {
    try {
        const action = {};
        action.bundleName = "com.sengmitnick.timelogger";
        action.abilityName = "com.sengmitnick.timelogger.ServiceAbility";
        action.messageCode = GETAUTHORIZATION;
        action.abilityType = 0;

        var result = await FeatureAbility.callAbility(action);
        var ret = JSON.parse(result);
        if (ret.code == SUCCESS) {
            console.info('getAuthorization result is:' + JSON.stringify(ret));
            if (!ret.data) return ''
            return JSON.parse(ret.data)?.authorization;
        } else {
            console.error('getAuthorization error code:' + JSON.stringify(ret.code));
        }
    } catch (err) {
        console.error('getAuthorization failed. Cause: ' + err.toString());
    }
    return ''
}

export async function checkAuthorization() {
    const Authorization = await getAuthorization();
    if (!Authorization) {
        router.push({ uri: "pages/login/login" });
        throw new Error('Authorization 不存在')
    }
    return Authorization
}

async function setAuthorization(authorization) {
    try {
        const action = {};
        action.bundleName = "com.sengmitnick.timelogger";
        action.abilityName = "com.sengmitnick.timelogger.ServiceAbility";
        action.data = { authorization }
        action.messageCode = SETAUTHORIZATION;
        action.abilityType = 0;

        var result = await FeatureAbility.callAbility(action);
        console.info('setAuthorization result is:' + result);

        var ret = JSON.parse(result);
        if (ret.code == SUCCESS) {
            console.info('setAuthorization result is:' + JSON.stringify(ret));
            return ret.data
        } else {
            console.error('setAuthorization error code:' + JSON.stringify(ret.code));
        }
    } catch (err) {
        console.error('setAuthorization failed. Cause: ' + err.toString());
    }
}

export async function login(params) {
    try {
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/login/account",
            { method: 'POST', extraData: params, }
        );
        var ret = JSON.parse(value.result);
        console.info('login result is:' + value.result);
        console.info('login accessToken is:' + ret?.data?.accessToken);
        if (ret?.data?.accessToken) await setAuthorization(ret?.data?.accessToken);
        return ret;
    } catch (err) {
        console.error('login failed. Cause: ' + err.toString());
    }
    return false;
}

export async function register(params) {
    try {
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/login/register",
            { method: 'POST', extraData: params, }
        );
        var ret = JSON.parse(value.result);
        console.info('register result is:' + value.result);
        console.info('register accessToken is:' + ret?.data?.accessToken);
        if (ret?.data?.accessToken) await setAuthorization(ret?.data?.accessToken);
        return true;
    } catch (err) {
        console.error('register failed. Cause: ' + err.toString());
    }
    return false;
}

export async function outLogin() {
    try {
        let httpRequest = http.createHttp();
        await httpRequest.request(
            BASEURL + "/login/outLogin",
            { method: 'POST', extraData: {}, }
        );
        await setAuthorization("");
        return true;
    } catch (err) {
        console.error('login failed. Cause: ' + err.toString());
    }
    return false;
}

async function updateToken(result, cb, ret) {
    if (["401"].includes(result.errorCode)) {
        try {
            const Authorization = await checkAuthorization()
            let httpRequest = http.createHttp();
            const value = await httpRequest.request(
                BASEURL + "/updateToken",
                { method: 'POST', header: { Authorization } }
            );
            console.info('updateToken result is:' + value.result);
            console.info('updateToken accessToken is:' + ret?.data?.accessToken);
            var ret = JSON.parse(value.result);
            if (ret?.data?.accessToken) await setAuthorization(ret?.data?.accessToken);
            return cb();
        } catch (err) {
            console.error('updateToken failed. Cause: ' + err.toString());
        }
        return false
    }
    return ret
}

export async function currentUser() {
    try {
        const Authorization = await checkAuthorization()
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/currentUser",
            { header: { Authorization } }
        );
        var ret = JSON.parse(value.result);
        console.info('currentUser result is:' + value.result);
        return updateToken(ret, currentUser, ret?.data);
    } catch (err) {
        console.error('currentUser failed. Cause: ' + err.toString());
    }
}

export async function listEventType(parentId = null) {
    try {
        const Authorization = await checkAuthorization()
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/event-type/list",
            { header: { Authorization }, extraData: { parentId } }
        );
        var ret = JSON.parse(value.result);
        console.info('listEventType result is:' + value.result);
        return updateToken(ret, () => listEventType(parentId), ret?.data);
    } catch (err) {
        console.error('listEventType failed. Cause: ' + err.toString());
    }
}

export async function listEventLog(params) {
    try {
        const Authorization = await checkAuthorization()
        let httpRequest = http.createHttp();
        const extraData = { current: 1, pageSize: 10, ...params };
        console.info('listEventLog extraData is:' + JSON.stringify(extraData));
        const value = await httpRequest.request(
            BASEURL + "/event-log/list",
            { header: { Authorization }, extraData }
        );
        var ret = JSON.parse(value.result);
        console.info('listEventLog result is:' + value.result);
        return updateToken(ret, () => listEventType(params), ret?.data);
    } catch (err) {
        console.error('listEventLog failed. Cause: ' + err.toString());
    }
}

export async function monthEventLog(params) {
    try {
        const Authorization = await checkAuthorization()
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/event-log/month",
            { header: { Authorization }, extraData: params }
        );
        var ret = JSON.parse(value.result);
        console.info('monthEventLog result is:' + value.result);
        return updateToken(ret, () => listEventType(params), ret?.data);
    } catch (err) {
        console.error('monthEventLog failed. Cause: ' + err.toString());
    }
}

export async function statEventLog(params) {
    try {
        const Authorization = await checkAuthorization()
        let httpRequest = http.createHttp();
        const value = await httpRequest.request(
            BASEURL + "/event-log/stat",
            { header: { Authorization }, extraData: params }
        );
        var ret = JSON.parse(value.result);
        console.info('statEventLog result is:' + value.result);
        return updateToken(ret, () => listEventType(params), ret?.data);
    } catch (err) {
        console.error('statEventLog failed. Cause: ' + err.toString());
    }
}